package Socket1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private static DatagramSocket socket;

    public UdpEchoServer(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }

    private static void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            DatagramPacket request = new DatagramPacket(new byte[1024],1024);
            socket.receive(request);
            String requestStr = new String(request.getData(),0,request.getLength());
            String responseStr=process(requestStr);

            DatagramPacket reponse=new DatagramPacket(responseStr.getBytes(),responseStr.getBytes().length,
                    request.getAddress(),request.getPort());
            socket.send(reponse);
            System.out.printf("clentIp: %s    port:%d     request:%s     reponse:%s\n",
                    request.getAddress(),request.getPort(),requestStr,responseStr);
        }


    }

    private static String process(String requestStr) {
        return requestStr;
    }


    public static void main(String[] args) throws IOException {
      UdpEchoServer server=new UdpEchoServer(8888);
      server.start();
    }



}
